package com.ruoyi.web.controller.word;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.word.service.ICommonWordCorrectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import static com.ruoyi.common.utils.SecurityUtils.getLoginUser;

/**
 * Created by Liuzy
 * Date: 2021/7/19
 * Description: 单词纠错后端controller
 */
@RestController
@RequestMapping("/word/correction")
public class CommonWordCorrectionController extends BaseController {

    @Autowired
    private ICommonWordCorrectionService biz;

    @GetMapping(value="/find")
    public R find(String sort, String order, String page, String size, String word, Integer isDeal,
                  String userName, String qssj, String jzsj){
        try{
            if(StringUtils.isEmpty(sort))
                sort = "p.add_time";
            else
                sort = "p." + sort;
            startPage();
            return  R.data(new PageInfo<>(biz.findByWhereStr(buildParam(word, isDeal, userName, qssj, jzsj), sort, order)));
        }catch (Exception e){
            e.printStackTrace();
        }
        return R.fail();
    }

    @GetMapping("/dealBatch")
    public R dealBatch(@RequestParam("id") Long id){
        try {
           int i =  biz.dealBatch(id, getLoginUser());
           if (i > 0 ){
               return R.ok();
           }
        }catch (Exception e){
            logger.error("correction-dealBatch", e);
        }
        return R.fail();
    }

    @DeleteMapping("/del/{id}")
    public R del(@PathVariable Long id){
        try {
            int i = biz.del(id);
            if (i > 0){
                return R.ok();
            }
        }catch (Exception e){
            logger.error("correction-del", e);
        }
        return R.fail();
    }

    public String buildParam(String word, Integer isDeal, String userName, String qssj, String jzsj) {
        StringBuilder whereStr = new StringBuilder("");
        if(StringUtils.isNotEmpty(qssj))
            whereStr.append(" and p.add_time >= '" + qssj + "'");
        if(StringUtils.isNotEmpty(jzsj))
            whereStr.append(" and p.add_time <= '" + jzsj + "'");
        if(StringUtils.isNotEmpty(word))
            whereStr.append(" and p.word like '%" + word + "%'");
        if(StringUtils.isNotEmpty(userName))
            whereStr.append(" and p.user_name ='" + userName + "'");
        if(isDeal != null)
            whereStr.append(" and p.is_deal = " + isDeal);
        return whereStr.toString();
    }
}
